﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;

namespace CommonLibrary.Common
{
    public class NodeHelp
    {
        DataTable _dt;
        string _id;
        string _name;
        string _rootValue;
        string _supId;
        string _filter;

        /// <summary>
        ///  treeview 填充帮助类
        /// </summary>
        /// <param name="tv">需要填充的树</param>
        /// <param name="dt">数据源</param>
        /// <param name="id">数据源中的值列</param>
        /// <param name="name">数据源中的显示列</param>
        /// <param name="supId">数据源中的上级值列</param>
        /// <param name="filter">根节点的条件 例 "id=0"</param>
        public NodeHelp(DataTable dt, string id, string name, string supId, string filter)
        {
            _dt = dt;
            _id = id;
            _name = name;
            _supId = supId;
            _filter = filter;
        }

        /// <summary>
        /// 将子节点填充到树 
        /// 转化为 TreeNode[]
        /// TreeNodeCollection.CopyTo(TreeNode[] nodeArray, int index) 
        /// </summary>
        public TreeNodeCollection FillNodeList()
        {
            TreeNode _tn = new TreeNode();
            
            var drs = _dt.Select(_filter);
            foreach (var dr in drs)
            {
                TreeNode rootNode = new TreeNode(dr[_name].ToString());
                NodeTag nh = new NodeTag
                {
                    Text = rootNode.Text,
                    Value = dr[_id].ToString(),
                    bz = string.Empty,
                    level = 0,
                };
                rootNode.Tag = nh;

                _tn.Nodes.Add(rootNode);
            }
            foreach (TreeNode node in _tn.Nodes)
            {

                GetChildNode(node, (node.Tag as NodeTag).Value);
            }
            TreeNode[] nodeArray = new TreeNode[_tn.Nodes.Count];
            return _tn.Nodes;

        }

        private void GetChildNode(TreeNode supNode, string supId)
        {

            DataRow[] drs = _dt.Select(_supId + " = " + supId);
            if (drs.Length == 0) return;
            foreach (var dr in drs)
            {
                TreeNode childNodes = new TreeNode(dr[_name].ToString());
                NodeTag nh = new NodeTag
                {
                    Text = childNodes.Text,
                    Value = dr[_id].ToString(),
                    bz = string.Empty,
                    level = 0,
                };
                childNodes.Tag = nh;
                GetChildNode(childNodes, (childNodes.Tag as NodeTag).Value);
                supNode.Nodes.Add(childNodes);
            }
        }
    }
}
